<template>
	<view class="container" style="padding-bottom: 100px" v-if="isLoaded">
		<!-- 表单 -->
		<view class="content" style="padding: 0 30rpx 120rpx; background-color: #fff">
			<li-form>
				<uni-section title="基础信息" title-color="#f3c45d" titleFontSize="32rpx">
					<template #decoration>
						<view class="decoration"></view>
					</template>
				</uni-section>

				<li-form-item label="券类型">
					<li-picker @change="onCouponTypeChange($event)" v-model="form.typeId" :rangeList="couponTypeEnum" />
				</li-form-item>
				<li-form-item label="券名称" required>
					<li-input v-model="form.name" rule="trim" prop="name" v-on:blur="onBlurEvent" />
				</li-form-item>
				<li-form-item label="券面值" :border="false" v-if="form.typeId == 1">
					<li-input style="flex: 1" v-model="form.parValue" rule="float" prop="parValue"></li-input>
				</li-form-item>
				<li-form-item label="券折扣" :border="false" v-if="form.typeId == 3">
					<li-input style="flex: 1" v-model="form.parValue" rule="int" prop="parValue">%。 备注：打7七折,请填写70</li-input>
				</li-form-item>
				<li-form-item label="使用有效期类型" label-width="110" :border="false">
					<li-picker
						class="f1"
						:rangeList="[
							{ id: 0, text: '自定义日期' },
							{ id: 1, text: '相对有效期' }
						]"
						v-model="form.validityType"
						v-on:change="onValidityTypeChange($event)"
					></li-picker>
				</li-form-item>
				<li-form-item label="自定义日期" v-if="form.validityType == 0" :border="false">
					<uni-datetime-picker v-model="form.validityObject" type="datetimerange" rangeSeparator="至" />
				</li-form-item>
				<li-form-item label="有效天数" v-if="form.validityType == 1">
					<li-input v-model="form.validDay" rule="int" prop="validDay" />
				</li-form-item>
				<li-form-item label="可用周期">
					<li-picker v-model="form.cycleType" :rangeList="cycleTypeEnum" v-on:change="form.cycelValue = []" />
				</li-form-item>
				<li-form-item v-show="form.cycleType == 1">
					<li-checkbox :range-list="weekEnumable" v-model="form.cycelValue" />
				</li-form-item>
				<li-form-item v-show="form.cycleType == 2">
					<li-checkbox :range-list="dayEnum" v-model="form.cycelValue" />
				</li-form-item>

				<li-form-item label="适用商品">
					<li-picker
						v-model="form.foodRange"
						:rangeList="[
							{
								id: 0,
								text: '全部商品'
							},
							{
								id: 1,
								text: '指定适用'
							},
							{
								id: 2,
								text: '指定不适用'
							}
						]"
					/>
				</li-form-item>
				<li-form-item :border="false" v-if="form.foodRange != 0">
					<view style="padding-left: 80px">
						<view style="display: flex; align-items: center">
							<li-picker
								class="f1"
								style="background-color: #fff; margin-right: 5px"
								v-model="form.appointType"
								:rangeList="[
									{
										id: 1,
										text: '指定菜品'
									},
									{
										id: 2,
										text: '指定类型'
									}
								]"
							/>
							<button size="mini" style="background-color: #f3c45d; color: #fff" v-on:click="btnChooseFoodOrTypeClick(form.appointType)">
								选择{{ form.appointType == 1 ? '菜品' : '类型' }}
							</button>
						</view>
					</view>
				</li-form-item>
				<!-- food -->
				<view class="spec-container" v-if="form.appointType == 1 && form.foodRange != 0">
					<view class="spec-body">
						<block v-if="form.foodList.length > 0">
							<view>
								<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0; background-color: #cacaca">
									<view class="is-default" style="background-color: transparent">菜品名称</view>
									<view class="spec-name task-price">菜品类型</view>
									<view class="price task-option">菜品规格</view>
									<view class="price task-option">菜品价格</view>
									<view class="btns task-btn">操作</view>
								</view>
							</view>
							<view v-for="(item, index) in form.foodList" :key="item.id" class="items">
								<view class="is-default">
									<text>
										{{ item.name }}
									</text>
								</view>
								<text>
									{{ item.foodTypeName }}
								</text>
								<view class="price task-option">
									<text>
										{{ item.foodSpecName }}
									</text>
								</view>
								<view class="price task-option">
									<text>
										{{ item.posPrice }}
									</text>
								</view>
								<view class="btns task-btn">
									<text class="btn btn-del" @click="btnDelTableItemClick(index, 1)" style="margin-left: 8px">删除</text>
								</view>
							</view>
						</block>
						<block v-else>暂无菜品，请点击右上角添加~~</block>
					</view>
				</view>

				<!-- foodType -->
				<view class="spec-container" v-if="form.appointType == 2 && form.foodRange != 0">
					<view class="spec-body">
						<block v-if="form.foodcategoryList.length > 0">
							<view>
								<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
									<view class="spec-name" style="justify-content: unset">菜品类型</view>
									<view class="btns task-btn">操作</view>
								</view>
							</view>
							<view v-for="(item, index) in form.foodcategoryList" :key="item.id" class="items">
								<view class="spec-name" style="justify-content: unset">
									{{ item.name }}
								</view>

								<view class="btns task-btn">
									<text class="btn btn-del" @click="btnDelTableItemClick(index, 2)" style="margin-left: 8px">删除</text>
								</view>
							</view>
						</block>
						<block v-else>暂无菜品类型，请点击右上角添加~~</block>
					</view>
				</view>
				<view style="height: 40rpx"><!-- 占位符 --></view>
				<uni-section title="优惠券使用规则" title-color="#f3c45d" titleFontSize="32rpx">
					<template #decoration>
						<view class="decoration"></view>
					</template>
				</uni-section>
				<li-form-item label-width="110" label="优惠券可用渠道" :border="false">
					<li-checkbox class="fs12" v-model="form.channelValue" :rangeList="channelTypeEnum" />
				</li-form-item>
				<li-form-item label="最低消费金额" label-width="100" :border="false">
					<li-input class="f1" v-model="form.parValue" rule="float" prop="parValue"></li-input>
				</li-form-item>
				<li-form-item label="是否重复使用" label-width="100" :border="false">
					<li-picker class="f1" v-model="form.reusable" :rangeList="booleanEnum" />
				</li-form-item>
				<view style="height: 40rpx"><!-- 占位符 --></view>
				<uni-section title="其他设置" title-color="#f3c45d" titleFontSize="32rpx">
					<template #decoration>
						<view class="decoration"></view>
					</template>
				</uni-section>
				<li-form-item label="券说明">
					<li-textarea placeholder="请填写优惠券介绍（C端用户可见。详细使用规则设置为“不显示”时，券说明为必填项）" v-model="form.description"></li-textarea>
				</li-form-item>
				<li-form-item label="券备注">
					<li-textarea v-model="form.remark" placeholder="请填写优惠券备注（C端用户不可见）"></li-textarea>
				</li-form-item>
			</li-form>
		</view>

		<li-bottom-btns :mode="mode" @btnDelClick="btnDelClick" @btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick" />

		<!-- food Popup -->

		<next-tree
			ref="foodCategoryTreeSelector"
			:treeData="foodCategoryList"
			labelKey="name"
			valueKey="id"
			checkStrictly
			:selectParent="true"
			:funcMode="'checkbox'"
			@confirm="foodCategoryTreeConfirm"
		/>

		<!-- foodType Popup -->
		<u-popup :show="showAddFood" @close="closePopupAddFood" @open="openPopupAddFood" :closeable="true">
			<view class="layout" style="height: 90vh; width: 100vw; background-color: #f7f8fa; font-size: 12px; display: flex">
				<view class="layout-left" style="height: 100%; width: 40vw; overflow-y: scroll">
					<view style="margin: 15rpx; background-color: #fff; border-radius: 10px; padding: 8px 4px" v-for="(item, index) in foodCategoryList" :key="item.id">
						<view class="fold" style="padding: 15rpx 15rpx 15rpx 0">
							<view class="tree-icon" style="margin: 0 5px" v-show="item.fold && item.children.length > 0" @click="unfold(index)">
								<!-- 向右箭头 -->
								<image style="width: 8px; height: 8px" src="/static/images/icon/down.png"></image>
							</view>
							<view @click="unfold(index)" style="margin: 0 5px" class="tree-icon" v-show="!item.fold && item.children.length > 0">
								<!-- 向下箭头 -->
								<image style="width: 8px; height: 8px" src="/static/images/icon/right.png"></image>
							</view>
							<view
								:style="{
									color: foodCategoryId == item.id ? '#f3c45d' : '#000',
									paddingLeft: item.children.length == 0 ? '20px' : '0px'
								}"
								@click="onItemClick(item)"
							>
								{{ item.name }}
							</view>
						</view>
						<block v-if="item.fold">
							<view v-for="(item1, index1) in item.children" class="subtree" :key="item1.id" style="display: flex; padding: 15rpx 15rpx 15rpx 0">
								<view
									class="tree-content"
									style="padding-left: 30px; padding-right: 20rpx"
									:style="{
										color: foodCategoryId == item1.id ? '#f3c45d' : '#000'
									}"
									@click="onItemClick(item1)"
								>
									<text>{{ item1.name }}</text>
								</view>
							</view>
						</block>
					</view>
				</view>
				<view class="layout-right" style="height: 100%; width: 60vw; overflow-y: scroll; padding-top: 40px">
					<block v-if="foodList != null && foodList.length > 0">
						<view class="food-items" style="font-size: 12px" v-for="(food, index) in foodList" :key="index">
							<image class="image" :src="food.image" style="align-self: center" />
							<view class="right" style="padding-bottom: 0">
								<text>名称：{{ food.name }}</text>
								<view class="mt-10">
									<text style="border: 1px solid #f7f8fa">规格：{{ food.foodSpecName }}</text>
								</view>
								<view class="mt-10">
									<text>价格：</text>
									<text class="text-red">￥{{ food.posPrice }}</text>
								</view>
							</view>
							<view class="btn" style="display: flex; align-items: center">
								<text
									@click="onPopItemClick(food)"
									class="btn-yellow"
									style="border-radius: 8px; padding: 3px 5px; color: #fff"
									:style="{
										'background-color': form.foodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '#f56c6c' : '#f3c45d'
									}"
								>
									{{ form.foodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '取消' : '选择' }}
								</text>
							</view>
							<!--          <view class="btn" style="display: flex; align-items: center">
                <text
                  style="
                    border: 1px solid #cacaca;
                    padding: 3px 5px;
                    border-radius: 8px;
                    background-color: #22a7f2;
                    color: #fff;
                  "
                  @click="onPopItemClick(food)"
                  >选择</text
                >
              </view> -->
						</view>
					</block>
					<block v-else>
						<view style="display: flex; height: 100%; justify-content: center; justify-content: center">
							<u-empty />
						</view>
					</block>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
import liFormMixin from '../../../mixins/liFormMixin';
import { GetFoodCouponById, AddFoodCoupon, DelFoodCouponById, EditFoodCoupon } from '../../../common/modules/catering.js';
import { GetFoodCategoryList, GetFood } from '../../../common/api.js';
import { transferTypeEnum } from '../../../common/dataTransfer.js';
import { utoast } from '../../../utils/uniUtils.js';
import { checkerType, modeEnum, booleanEnum, couponTypeEnum, weekEnumable, dayEnum, cycleTypeEnum, channelTypeEnum } from '../../../constants/normalConstants.js';
import treeSelector from '@/components/tree-selector/tree-selector.vue';
import dateUtils from '../../../utils/date.js';
import date from '../../../utils/date.js';
import { toastIconEnum } from '../../../constants/uiConstants.js';

export default {
	components: {
		treeSelector
	},
	mixins: [liFormMixin],
	async onLoad(options) {
		this.loadEvent(options, this);
	},

	async mounted() {
		this.mountedEvent(this, {
			name: '',
			typeId: 1,
			parValue: 0,
			validityType: 0,
			startDate: dateUtils.getTomorrow(),
			endDate: dateUtils.getDate(2),
			validDay: 0,
			cycleType: 0,
			cycelValue: '',
			foodRange: 0,
			appointType: 1,
			channelValue: [1, 2, 3],
			reusable: 1,
			description: '',
			remark: '',
			foodList: [],
			foodcategoryList: [],
			validityObject: [dateUtils.getTomorrow(), dateUtils.getDate(2)]
		});
	},
	data: function () {
		return {
			foodList: [],
			foodCategoryList: [],
			channelTypeEnum,
			cycleTypeEnum,
			weekEnumable,
			dayEnum,
			modeEnum,
			couponTypeEnum,
			booleanEnum,
			subject: '优惠券',
			rootRoute: 'workbench',
			routeName: 'coupon',
			mode: 'add',
			isLoaded: false,
			id: null,
			/* Form */
			form: null,
			/* Popup */
			showAddFood: false,
			// DataTransfer
			transferRules: [
				/*    {
          name: "title",
          type: transferTypeEnum.trim,
        },
        {
          name: "rechargeAmount",
          type: transferTypeEnum.int,
        },
        {
          name: "discountValue",
          type: transferTypeEnum.int,
        }, */
			],
			//FormRules
			rules: [
				{
					name: 'name',
					checkType: checkerType.endNotNull,
					errorMsg: '优惠券名称不能为空~~'
				}
			],
			lock: false, // throttle lock

			/* extra data */
			foodCategoryId: null
			/* extra form rule */
			/* extra transfer */
		};
	},

	methods: {
		onBlurEvent(e) {
			this.formBlur(e, this);
		},

		async getData() {
			this.form = (await GetFoodCouponById(this.id)).data;
		},

		async getOtherData() {
			// ..
			this.foodCategoryList = (await GetFoodCategoryList()).data.list;
			this.foodCategoryList.forEach((element) => {
				element.label = element.name;
				element.fold = true;
				element.active = false;
				if (element.children.length > 0) {
					element.children.map((item) => {
						item.label = item.name;
						item.fold = true;
					});
				}
			});

			if (this.foodCategoryList.length > 0) {
				this.foodCategoryList[0].active = true;
			}
		},

		async insertData() {
			return AddFoodCoupon(this.form);
		},

		async delData() {
			return await DelFoodCouponById(this.id);
		},

		async editData() {
			return await EditFoodCoupon(this.form);
		},

		async btnDelClick() {
			await this.formDelete(this);
		},

		async btnEditOrSaveSubmitClick() {
			if (this.form.cycleType == 1 && this.form.cycelValue.length == 0) {
				utoast('请选择可用周期', toastIconEnum.error);
				return;
			}

			if (this.form.cycleType == 2 && this.form.cycelValue.length == 0) {
				utoast('请选择可用周期', toastIconEnum.error);
				return;
			}
			if (this.form.validityObject.length < 2) {
				utoast('请选择有效期', toastIconEnum.error);
				return;
			}

			await this.formInsertOrEdit(this);
		},

		/* Form Event */
		onCouponTypeChange: function (e) {
			const couponType = e.detail.value;
			if (couponType == 1) {
				this.form.parValue = 0;
			} else if (couponType == 3) {
				this.form.parValue = 100;
			}
		},

		btnDelTableItemClick: function (idx, type) {
			this.form[type == 1 ? 'foodList' : 'foodcategoryList'].splice(idx, 1);
		},

		onValidityTypeChange: function (e) {
			const validityType = e.detail.value;
			if (validityType == 1) {
				this.form.validityObject = [dateUtils.getTomorrow(), dateUtils.getDate(2)];
			} else {
				this.form.validDay = 0;
			}
		},
		/* extra method */
		btnChooseFoodOrTypeClick: function (type) {
			// food
			if (type == 1) {
				// food type
				this.openPopupAddFood();
			} else if (type == 2) {
				this.$refs.foodCategoryTreeSelector.showTree = true;
			}
		},

		foodCategoryTreeConfirm: function (e) {
			console.log('e', e);
			this.form.foodcategoryList = e;
		},

		closePopupAddFood: function () {
			this.showAddFood = false;
		},
		openPopupAddFood: async function () {
			this.foodCategoryId = this.foodCategoryList[0].id;
			const res = await GetFood({
				pageNum: 1,
				pageSize: 9999,
				foodCategoryId: this.foodCategoryList[0].id
			});

			this.foodList = res.data.list.filter((item) => item.type == 1);
			this.showAddFood = true;
		},
		unfold(index) {},
		onItemClick: async function (item) {
			console.log(item, 'item');
			if (this.foodCategoryId == item.id) return;
			const res = await GetFood({
				pageNum: 1,
				pageSize: 9999,
				foodCategoryId: item.id
			});
			this.foodCategoryId = item.id;
			this.foodList = res.data.list.filter((item) => item.type == 1);
		},
		async onPopItemClick(food) {
			const res = this.form.foodList.some((itm) => itm.foodSpecId == food.foodSpecId);
			if (res) {
				const idx = this.form.foodList.findIndex((itm) => itm.foodSpecId == food.foodSpecId);
				this.form.foodList.splice(idx, 1);
			} else {
				this.form.foodList.push(food);
			}
		}
		//method put on the top
	}
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';

.spec-container {
	background-color: #fff;
	border-radius: 10px;
	margin: 10px 0;
	padding: 8px 4px;

	.spec-header {
		padding: 10px;
		border-bottom: 1px solid #ededed;
		display: flex;
		justify-content: space-between;
	}

	.spec-body {
		padding: 15px 10px;

		.items {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 12px;
			border-bottom: 1px solid #cacaca;
			padding: 8px 0;
			&:last-child {
				border-bottom: none;
			}

			.is-default {
				width: 80px;
				display: flex;
				justify-content: center;
				color: #000;
				background-color: #fff;
				.is-default-active {
					color: #fff;
					background-color: #fdc31d;
				}
			}

			.spec-name {
				flex: 1;
				display: flex;
				justify-content: center;
				&.task-price {
					width: 80px;
				}
			}

			.price {
				width: 80px;
				display: flex;
				justify-content: center;
				&.task-option {
					width: 60px;
				}
			}

			.btns {
				width: 90px;
				display: flex;
				justify-content: center;
				&.task-btn {
					width: 70px;
					font-size: 12px;
				}
			}

			.btn {
				border: 1px solid #ededed;
				padding: 12rpx 12rpx;
				border-radius: 5rpx;
				&.btn-del {
					background-color: #f56c6c;
					color: #fff;
				}
			}
		}
	}
}

.food-items {
	display: flex;
	padding: 5px;
	border: 1px solid #cacaca;
	border-radius: 8px;
	margin-bottom: 10px;
	margin-right: 10px;
	margin-left: 10px;
	.image {
		width: 160rpx;
		height: 100rpx;
		margin-right: 20rpx;
		border-radius: 8rpx;
		background-color: $bg-color-grey;
	}

	.right {
		flex: 1;
		// height: 160rpx;
		// overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: space-between;
		border-bottom: 1px #f8f8f8 solid;
		padding-bottom: 20rpx;

		.label {
			display: flex;
			margin-top: 10rpx;

			text {
				display: inline-block;
				padding: 0 8rpx;
				font-size: 20rpx;
				border: 1px #f3c45d solid;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}
		}

		.btn {
			display: flex;
			margin-top: 10rpx;

			text {
				display: inline-block;
				padding: 4rpx 16rpx;
				font-size: 24rpx;
				border: 1px #333 solid;
				border-radius: 8rpx;
				margin-right: 10rpx;
			}
		}
	}
}

.img {
	width: 20px;
	height: 20px;
}

.fold {
	display: flex;
}
.decoration {
	height: 30rpx;
	width: 4rpx;
	background-color: #f3c45d;
	border: 10rpx;
	margin-right: 20rpx;
	margin-left: -10rpx;
}
</style>
